package com.jcj.businesspool;

import com.google.protobuf.ByteString;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.TimeUnit;

/**
 * 测试基于Protobuf的实体对象传输
 */
@ChannelHandler.Sharable
public class HandlerServerBP extends ChannelInboundHandlerAdapter {

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {

        InformationProto.Information information = (InformationProto.Information) msg;
        System.out.println("具体数据内容:" + information.getContent());


        //反馈数据
        byte[] headerReturn = new byte[]{(byte) 0x3C, (byte) 0X3C};
        byte[] msgtypeReturn = new byte[]{(byte) 0x01};

        InformationProto.Information informationReturn = InformationProto.Information.newBuilder()
                .setHeader(ByteString.copyFrom(headerReturn))
                .setMsgtype(ByteString.copyFrom(msgtypeReturn))
                .setPersonnum(5252)
                .setPrice(123.66f)
                .setContent(information.getContent())
                .build();

        ctx.writeAndFlush(informationReturn);

    }


    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        //出现异常的时候执行的动作(打印并关闭通道)
        cause.printStackTrace();
        ctx.close();
    }

    /**
     * 新建立连接时触发的动作
     */
    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        Channel channel = ctx.channel();
        //System.out.println("打印channel:"+channel);
        //System.out.println("运行类型:"+channel.getClass());
        System.out.println("客户端: " + channel.remoteAddress() + "已连接上来");
    }

    /**
     * 连接断开时触发的动作
     */
    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
        Channel channel = ctx.channel();
        System.out.println("客户端: " + channel.remoteAddress() + "已断开");
    }

    /**
     * 通道处于活动状态触发的动作,该方法只会在通道建立时调用一次
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        Channel channel = ctx.channel();
        System.out.println("客户端: " + channel.remoteAddress() + "在线");
    }

    /**
     * 通道处于非活动状态触发的动作,该方法只会在通道失效时调用一次
     */
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        Channel channel = ctx.channel();
        System.out.println("客户端: " + channel.remoteAddress() + "掉线");
    }
}
